import React, { Fragment, useState } from 'react';
import { history } from 'umi';
import { Menu } from 'antd';
import * as Icon from '@ant-design/icons';

const { SubMenu } = Menu;

export default (prods) => {
  const [mode, handleMode] = useState(prods.mode);
  const [current, setCurrent] = useState('');

  const handleClick = (e) => {
    history.push(e.key);
    setCurrent(e.key);
  };
  // 实现菜单构建函数
  const createMenuListMap = (list) => {
    return list.map((item) => {
      if (item.children && item.children.length > 0) {
        // 若是当前循环到的菜单项有 children，那就返回 SubMenu，不然返回的直接是 Menu.Item
        return (
          <SubMenu
            key={item.path}
            onTitleClick={handleClick}
            title={
              <span>
                <span>{item.name}</span>
              </span>
            }
          >
            {
              // 根据当前菜单的 children 去生成其子菜单，因为菜单项 menuList 是个有终结的数据，且嵌套层数并不复杂，因此这里不用担忧递归会形成栈溢出的问题
              createMenuListMap(item.children)
            }
          </SubMenu>
        );
      } else {
        return (
          <Menu.Item key={item.path}>
            <span>{item.name}</span>
          </Menu.Item>
        );
      }
    });
  };

  return (
    <Menu
      style={{
        width: '100%',
      }}
      onClick={handleClick}
      selectedKeys={[current]}
      mode={mode}
    >
      <Fragment>{createMenuListMap(prods.data)}</Fragment>
    </Menu>
  );
};
